package models

import (
	"errors"
	"fmt"
	"reflect"
	"strings"
	"time"

	"github.com/astaxie/beego"
	"github.com/astaxie/beego/orm"
)

type Stateinstance struct {
	Id           string        `orm:"column(id);pk"`
	UserId       string        `orm:"column(user_id)"`
	Flowinstance *Flowinstance `orm:"column(flowinstance_id);rel(fk)"`
	State        *State        `orm:"column(state_id);rel(fk)"`
	Busyid       string        `orm:"column(busyid);null"`
	Busyname     string        `orm:"column(busyname);null"`
	Text         string        `orm:"column(text);null"`
	Classname    string        `orm:"column(classname);null"`
	Style        string        `orm:"column(style);type(jsonb);null"`
	Remark       string        `orm:"column(remark);null"`
	Opinions     string        `orm:"column(opinions);null"`
	Approver     string        `orm:"column(approver);null"`
	Result       int           `orm:"column(result);null"`
	Atime        time.Time     `orm:"column(atime);type(timestamp with time zone);null"`
	Status       int           `orm:"column(status)"`
	Isdelete     int           `orm:"column(isdelete)"`
	Ctime        time.Time     `orm:"column(ctime);type(timestamp with time zone)"`
	Creater      string        `orm:"column(creater)"`
	Utime        time.Time     `orm:"column(utime);type(timestamp with time zone)"`
	Updater      string        `orm:"column(updater)"`
}

func (t *Stateinstance) TableName() string {
	return "fsm_stateinstance"
}

func init() {
	orm.RegisterModel(new(Stateinstance))
}

// AddStateinstance insert a new Stateinstance into database and returns
// last inserted Id on success.
func AddStateinstance(m *Stateinstance) (id int64, err error) {
	o := orm.NewOrm()
	id, err = o.Insert(m)
	return
}

// GetStateinstanceById retrieves Stateinstance by Id. Returns error if
// Id doesn't exist
func GetStateinstanceById(id string) (v *Stateinstance, err error) {
	o := orm.NewOrm()
	v = &Stateinstance{Id: id}
	if err = o.Read(v); err == nil {
		return v, nil
	}
	//beego.Debug(v)
	beego.Debug(err)
	return v, err
}

// GetAllStateinstance retrieves all Stateinstance matches certain condition. Returns empty list if
// no records exist
func GetAllStateinstance(query map[string]string, fields []string, sortby []string, order []string,
	offset int64, limit int64) (ml []interface{}, err error) {
	o := orm.NewOrm()
	qs := o.QueryTable(new(Stateinstance))
	// query k=v
	for k, v := range query {
		// rewrite dot-notation to Object__Attribute
		k = strings.Replace(k, ".", "__", -1)
		if strings.Contains(k, "isnull") {
			qs = qs.Filter(k, (v == "true" || v == "1"))
		} else {
			qs = qs.Filter(k, v)
		}
	}
	// order by:
	var sortFields []string
	if len(sortby) != 0 {
		if len(sortby) == len(order) {
			// 1) for each sort field, there is an associated order
			for i, v := range sortby {
				orderby := ""
				if order[i] == "desc" {
					orderby = "-" + v
				} else if order[i] == "asc" {
					orderby = v
				} else {
					return nil, errors.New("Error: Invalid order. Must be either [asc|desc]")
				}
				sortFields = append(sortFields, orderby)
			}
			qs = qs.OrderBy(sortFields...)
		} else if len(sortby) != len(order) && len(order) == 1 {
			// 2) there is exactly one order, all the sorted fields will be sorted by this order
			for _, v := range sortby {
				orderby := ""
				if order[0] == "desc" {
					orderby = "-" + v
				} else if order[0] == "asc" {
					orderby = v
				} else {
					return nil, errors.New("Error: Invalid order. Must be either [asc|desc]")
				}
				sortFields = append(sortFields, orderby)
			}
		} else if len(sortby) != len(order) && len(order) != 1 {
			return nil, errors.New("Error: 'sortby', 'order' sizes mismatch or 'order' size is not 1")
		}
	} else {
		if len(order) != 0 {
			return nil, errors.New("Error: unused 'order' fields")
		}
	}

	var l []Stateinstance
	qs = qs.OrderBy(sortFields...)
	if _, err = qs.Limit(limit, offset).All(&l, fields...); err == nil {
		if len(fields) == 0 {
			for _, v := range l {
				ml = append(ml, v)
			}
		} else {
			// trim unused fields
			for _, v := range l {
				m := make(map[string]interface{})
				val := reflect.ValueOf(v)
				for _, fname := range fields {
					m[fname] = val.FieldByName(fname).Interface()
				}
				ml = append(ml, m)
			}
		}
		return ml, nil
	}
	return nil, err
}

// UpdateStateinstance updates Stateinstance by Id and returns error if
// the record to be updated doesn't exist
func UpdateStateinstanceById(m *Stateinstance) (err error) {
	o := orm.NewOrm()
	v := Stateinstance{Id: m.Id}
	// ascertain id exists in the database
	if err = o.Read(&v); err == nil {
		var num int64
		if num, err = o.Update(m); err == nil {
			fmt.Println("Number of records updated in database:", num)
		}
	}
	return
}

// DeleteStateinstance deletes Stateinstance by Id and returns error if
// the record to be deleted doesn't exist
func DeleteStateinstance(id string) (err error) {
	o := orm.NewOrm()
	v := Stateinstance{Id: id}
	// ascertain id exists in the database
	if err = o.Read(&v); err == nil {
		var num int64
		if num, err = o.Delete(&Stateinstance{Id: id}); err == nil {
			fmt.Println("Number of records deleted in database:", num)
		}
	}
	return
}

// GetStateByFlowIns 根据流程实例id获取状态
func GetStateByFlowIns(flowid string) (stateInses []Stateinstance, err error) {
	o := orm.NewOrm()
	qs := o.QueryTable(new(State))
	qs = qs.Filter("Isdelete", 0).Filter("Status", 1).Filter("Flowinstance", flowid).RelatedSel()
	_, err = qs.Limit(-1).All(&stateInses)
	return
}

// GetStartByFlowIns 根据流程实例id获取开始节点状态
func GetStartByFlowIns(flowid string) (stateIns Stateinstance, err error) {
	o := orm.NewOrm()
	qs := o.QueryTable(new(Stateinstance))
	qs = qs.Filter("Isdelete", 0).Filter("Status", 1).Filter("Flowinstance", flowid).RelatedSel()
	err = qs.Filter("Classname", "start").One(&stateIns)
	return
}

// GetEndByFlowIns 根据流程实例id获取结束节点状态
func GetEndByFlowIns(flowid string) (stateIns Stateinstance, err error) {
	o := orm.NewOrm()
	qs := o.QueryTable(new(Stateinstance))
	qs = qs.Filter("Isdelete", 0).Filter("Status", 1).Filter("Flowinstance", flowid).RelatedSel()
	err = qs.Filter("Classname", "end").One(&stateIns)
	return
}

// GetStateinstanceByFlowInsAndState 根据流程实例id和stateid获取节点实例
func GetStateinstanceByFlowInsAndState(flowid, state_id string) (stateIns Stateinstance, err error) {
	o := orm.NewOrm()
	qs := o.QueryTable(new(Stateinstance))
	qs = qs.Filter("Flowinstance", flowid).Filter("State", state_id)
	qs = qs.RelatedSel()
	err = qs.One(&stateIns)
	if err != nil {
		beego.Error(err)
	}
	return
}

func GetSfCaseBusyDoing(user *User) ([]orm.Params, error) {
	o := orm.NewOrm()
	qs := o.QueryTable(new(Stateinstance)).Filter("UserId", user.Role[0].Id).Filter("Busyname", "sf_case")
	qs = qs.Filter("Isdelete", 0).Filter("Status", 1)
	var l orm.ParamsList
	_, err := qs.Limit(-1).ValuesFlat(&l, "Busyid")
	if err != nil || len(l) < 1 {
		return nil, err
	}
	beego.Debug(l)

	ts := o.QueryTable("sf_case").Filter("Id__in", l).Filter("isdelete", 0).
		OrderBy("-utime").Filter("JyType", user.JdType)
	var e []orm.Params
	_, err = ts.Values(&e)
	return e, err
}

// GetBusyDoing 根据用户id和业务名称获取待办信息
func GetBusyDoing(user *User, bname string) ([]orm.Params, error) {
	o := orm.NewOrm()
	qs := o.QueryTable(new(Stateinstance)).Filter("UserId", user.Id).Filter("Busyname", bname)
	qs = qs.Filter("Isdelete", 0).Filter("Status", 1)
	var l orm.ParamsList
	_, err := qs.Limit(-1).ValuesFlat(&l, "Busyid")
	if err != nil || len(l) < 1 {
		return nil, err
	}
	beego.Debug(l)

	ts := o.QueryTable(bname).Filter("Id__in", l).Filter("isdelete", 0).OrderBy("-utime")
	var e []orm.Params
	_, err = ts.Values(&e)
	return e, err
}

// ReApply 根据用户id和业务id
// 将退回的流程实例和状态实例设置为玩成
func ReApply(userid, busyid string, fi *Flowinstance) (err error) {
	o := orm.NewOrm()
	var stinc Stateinstance
	qs := o.QueryTable(new(Stateinstance)).Filter("UserId", userid).Filter("Busyid", busyid)
	qs = qs.Filter("Isdelete", 0).Filter("Status", 1)
	err = qs.One(&stinc)
	stinc.Status = 2
	stinc.Opinions = "重新上报"
	fi.Status = 2
	o.Update(fi)
	return
}

// 终止流程
func StopFlow(user *User, fi *Flowinstance) (err error) {
	fi.Status = 0
	fi.Remark = ""
	fi.Updater = user.Abbr
	fi.Utime = time.Now()
	o := orm.NewOrm()
	_, err = o.Update(fi)
	return
}

// GetBusyFlowing 根据用户id和业务名称获取已处理完成流转中信息
func GetBusyFlowing(user *User, bname string) ([]orm.Params, error) {
	o := orm.NewOrm()
	qs := o.QueryTable(new(Stateinstance)).Filter("UserId", user.Id).Filter("Busyname", bname)
	qs = qs.Filter("Flowinstance__Status", 1)
	qs = qs.Filter("Isdelete", 0).Filter("Status", 2)
	var l orm.ParamsList
	_, err := qs.Limit(-1).ValuesFlat(&l, "Busyid")
	if err != nil || len(l) < 1 {
		return nil, err
	}
	ts := o.QueryTable(bname).Filter("Id__in", l).OrderBy("-utime")
	if bname == "sf_sfyy" {
		ts = ts.Filter("jy_type", user.JdType)
	}
	var e []orm.Params
	_, err = ts.Values(&e)
	return e, err

}
// GetBusyFlowing 根据用户id和业务名称获取已处理完成流转中信息
func GetBusyFlowingByUser(user *User, bname string) ([]orm.Params, error) {
	o := orm.NewOrm()
	//qs := o.QueryTable(new(Stateinstance)).Filter("UserId", user.Id).Filter("Busyname", bname)
	//qs = qs.Filter("Flowinstance__Status", 1)
	//qs = qs.Filter("Isdelete", 0).Filter("Status__gte", 2)
	//var l orm.ParamsList
	//_, err := qs.Limit(-1).ValuesFlat(&l, "Busyid")
	//if err != nil || len(l) < 1 {
	//	return nil, err
	//}
	ts := o.QueryTable(bname).Filter("cid", user.Id).Filter("status__gte", 2).OrderBy("-utime")
	//if bname == "sf_sfyy" {
	//	ts = ts.Filter("jy_type", user.JdType)
	//}
	var e []orm.Params
	_, err := ts.Values(&e)
	return e, err

}
// GetBusyFinish 根据用户id和业务名称获取流程结束信息
func GetBusyFinish(user *User, bname string) ([]orm.Params, error) {
	o := orm.NewOrm()
	qs := o.QueryTable(new(Stateinstance)).Filter("UserId", user.Id).Filter("Busyname", bname)
	qs = qs.Filter("Flowinstance__Status", 2)
	qs = qs.Filter("Isdelete", 0).Filter("Status", 2)
	var l orm.ParamsList
	_, err := qs.Limit(-1).ValuesFlat(&l, "Busyid")
	if err != nil || len(l) < 1 {
		return nil, err
	}
	ts := o.QueryTable(bname).Filter("Id__in", l).OrderBy("-utime")
	if bname == "sf_sfyy" {
		ts = ts.Filter("jy_type", user.JdType)
	}
	var e []orm.Params
	_, err = ts.Values(&e)
	return e, err
}

// SetBusyStart 设置业务流程状态为流程开始
func SetBusyStart(busyid, bname string) (err error) {
	o := orm.NewOrm()
	ts := o.QueryTable(bname).Filter("Id", busyid)

	_, err = ts.Update(orm.Params{
		"status": "2",
	})
	return
}


// GetStateinsByBusy 根据业务id获取状态实例
func GetStateinsByBusy(busyid string) (stateInses []Stateinstance, err error) {
	o := orm.NewOrm()
	qs := o.QueryTable(new(Stateinstance))
	qs = qs.Filter("Busyid", busyid).OrderBy("Ctime")
	_, err = qs.Limit(-1).All(&stateInses)
	return
}

// GetCurrentByUser 根据用户id和业务名称获取待办信息
func GetCurrentByUser(userid, busyid string) (*Stateinstance, error) {
	o := orm.NewOrm()
	var st Stateinstance
	beego.Debug(userid, busyid)
	qs := o.QueryTable(new(Stateinstance)).Filter("UserId", userid).Filter("Busyid", busyid)
	err := qs.Filter("Status", 1).One(&st)

	return &st, err
}
// GetCurrent 根据用户id和业务名称获取待办信息
func GetCurrent(busyid string) (*Stateinstance, error) {
	o := orm.NewOrm()
	var st Stateinstance
	qs := o.QueryTable(new(Stateinstance)).Filter("Busyid", busyid)
	err := qs.Filter("Status", 1).One(&st)

	return &st, err
}